package name.sraynal.srt;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SrtModificator extends Main {
	public static Pattern LINE_PATTERN = Pattern
			.compile("[ ]*(\\d\\d:\\d\\d:\\d\\d,\\d\\d\\d)[ ]+-->"
					+ "[ ]+(\\d\\d:\\d\\d:\\d\\d,\\d\\d\\d)[ ]*");
	private static Pattern MS_PATTERN = Pattern
			.compile("([+-])([\\d]+)[Mm][Ss]");
	private static Pattern S_PATTERN = Pattern.compile("([+-])([\\d]+)[Ss]");
	private static Pattern M_PATTERN = Pattern.compile("([+-])([\\d]+)[Mm]");
	private static Pattern H_PATTERN = Pattern.compile("([+-])([\\d]+)[Hh]");
	private String fileName;
	private long deltaMS;

	public SrtModificator(String fileName) {
		super();

		output("For <expand> mode, type E");
		String input = readInput().toLowerCase();

		if ("e".equals(input)) {
			try {
				new SrtExpander(fileName).run();
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.exit(1);
		}

		this.fileName = fileName;
		output("Please input the delta in the following form : +1m -3s");
		String deltaIn = readInput();
		try {
			setDelta(deltaIn.split(" "));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		SrtAnalyzer analyzer = new SrtAnalyzer(args[0]);
		System.out.println("Begins at : " + analyzer.getStartDate());
		System.out.println("  Ends at : " + analyzer.getEndDate());

		SrtModificator mod = new SrtModificator(args[0]);
		mod.execute();
	}

	private void execute() throws Exception {
		File file = new File(fileName);
		File dir = new File("C:\\out");
		dir.mkdirs();
		File out = new File(dir, file.getName());
		SimpleDateFormat format = new SimpleDateFormat("KK:mm:ss,SSS");
		BufferedReader reader = new BufferedReader(new FileReader(file));
		BufferedWriter writer = new BufferedWriter(new FileWriter(out));
		String read;

		while ((read = reader.readLine()) != null) {
			Matcher matcher = LINE_PATTERN.matcher(read);

			if (matcher.matches()) {
				Date current = format.parse(matcher.group(1));
				current.setTime(current.getTime() + deltaMS);
				writer.append(format.format(current)).append(" --> ");
				current = format.parse(matcher.group(2));
				current.setTime(current.getTime() + deltaMS);
				writer.append(format.format(current)).append("\r\n");
			} else {
				writer.append(read).append("\r\n");
			}
		}

		reader.close();
		writer.close();
		output("Replace ? default N.");
		String resp = readInput();
		if (resp.toLowerCase().startsWith("y")) {
			file.renameTo(new File(out.getParentFile(), file.getName() + "old"));
			out.renameTo(file);
			output("Created output file : " + file);
		} else {
			output("Created output file : " + out);
			String command = "explorer " + out.getParent();
			Runtime.getRuntime().exec(command);
		}
	}

	private void setDelta(String[] args) throws Exception {
		Matcher matcher;
		long result = 0;

		for (int i = 0; i < args.length; i++) {
			long added = 0;
			if ((matcher = MS_PATTERN.matcher(args[i])).matches()) {
				added = Long.parseLong(matcher.group(2));
			} else if ((matcher = S_PATTERN.matcher(args[i])).matches()) {
				added = Long.parseLong(matcher.group(2)) * 1000;
			} else if ((matcher = M_PATTERN.matcher(args[i])).matches()) {
				added = Long.parseLong(matcher.group(2)) * 1000 * 60;
			} else if ((matcher = H_PATTERN.matcher(args[i])).matches()) {
				added = Long.parseLong(matcher.group(2)) * 1000 * 60 * 60;
			} else {
				throw new Exception("Specify time length please. Argument ["
						+ args[i] + "] " + "does not mean anything");
			}

			if ("+".equals(matcher.group(1))) {
				result += added;
			} else {
				result -= added;
			}
		}
		deltaMS = result;
	}
}
